package com.socool.sinofaith.adapter;

import java.util.ArrayList;
import java.util.List;
import com.socool.sinofaith.R;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifSubTemplateDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.SifSubTaskBean;
import com.socool.sinofaith.ui.AnswerQuestionActivity;
import com.socool.sinofaith.ui.ChildTaskActivity;
import com.socool.sinofaith.ui.PreviewQuestionActivity;
import com.socool.sinofaith.ui.QuestionDetailActivity;
import com.socool.sinofaith.ui.SubTaskActivity;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SubTaskAdapter extends BaseAdapter {

	private List<SifSubTaskBean> mdatas = new ArrayList<SifSubTaskBean>();
	private LayoutInflater inflater;

	private Context mContext;
	private ListView mListview;
	private String userMobile ;
	
	private LoadingDialog mLoadingDialog;

	public List<SifSubTaskBean> getMdatas() {
		return mdatas;
	}

	public void setMdatas(List<SifSubTaskBean> mdatas) {

		this.mdatas = mdatas;
	}

	public void addDatas(List<SifSubTaskBean> mdatas) {
		this.mdatas.addAll(mdatas);
		this.notifyDataSetChanged();
	}

	public SubTaskAdapter(Context _context, ListView listview) {
		super();
		mContext = _context;
		inflater = LayoutInflater.from(_context);
		mListview = listview;
		mLoadingDialog=new LoadingDialog(mContext);
		userMobile=getSPString("UserMobile");
	}

	@Override
	public int getCount() {
		if (mdatas != null) {
			return mdatas.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {

		ViewHolder mViewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.subtask_listitem, null);
			mViewHolder = new ViewHolder();
			mViewHolder.templateNameTextView = (TextView) convertView
					.findViewById(R.id.templateNameTextView);
			mViewHolder.taskdescTextView = (TextView) convertView
					.findViewById(R.id.taskdescTextView);
			mViewHolder.btn01 = (Button) convertView.findViewById(R.id.btn01);
			mViewHolder.btn02 = (Button) convertView.findViewById(R.id.btn02);
			mViewHolder.btnpreview=(Button) convertView.findViewById(R.id.btnpreview);
			convertView.setTag(mViewHolder);

		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}
		mViewHolder.templateNameTextView.setText(mdatas.get(position)
				.getTemplateName());
		String haschild = mdatas.get(position).getHasChild();
		mViewHolder.taskdescTextView.setTag(position);
		mViewHolder.btn01.setTag("btn01" + position);
		mViewHolder.btn02.setTag("btn02" + position);
		if (!TextUtils.isEmpty(haschild) && haschild.equals("1")) {

			mViewHolder.btn02.setVisibility(View.VISIBLE);
			mViewHolder.btn02.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(mContext,
							ChildTaskActivity.class);
					intent.putExtra("subtaskid", mdatas.get(position)
							.getSubTask_ID());
					intent.putExtra("taskid", mdatas.get(position).getTask_ID());
					intent.putExtra("taskName", mdatas.get(position).getTemplateName());
					mContext.startActivity(intent);

				}
			});
			new AsyncTask<Void, Void, String>() {

				@Override
				protected String doInBackground(Void... arg0) {
					SifSubTemplateDao sifSubTemplateDao = new SifSubTemplateDao(
							mContext);
					return sifSubTemplateDao.getSifSubTemplateCount(mdatas.get(
							position).getSubTask_ID())
							+ "";
				}

				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					((TextView) mListview.findViewWithTag(position))
							.setText("子任务：" + result);
					;
				}

			}.execute();

		} else {

			new AsyncTask<Void, Void, ArrayList<QuestionAnswerBean>>() {

				@Override
				protected ArrayList<QuestionAnswerBean> doInBackground(
						Void... arg0) {
					QuestionAnswerDao questionAnswerDao = new QuestionAnswerDao(
							mContext);
					ArrayList<QuestionAnswerBean> totalAnswerlist = questionAnswerDao
							.queryBySql("select * from "
									+ QuestionAnswerBean.TABLENAME
									+ " where Task_ID='"
									+ mdatas.get(position).getTask_ID()
									+ "' and SubTask_ID='"
									+ mdatas.get(position).getSubTask_ID()
									+ "'  and Submiter='"
									+ userMobile
									+ "'");
					return totalAnswerlist;
				}

				@Override
				protected void onPostExecute(
						ArrayList<QuestionAnswerBean> result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					Button btn01 = (Button) mListview.findViewWithTag("btn01"
							+ position);
					Button btn02 = (Button) mListview.findViewWithTag("btn02"
							+ position);
					if (null != result && result.size() > 0) {

						for (int i = 0; i < result.size(); i++) {
							final QuestionAnswerBean answerBean = result.get(i);
							try {
								Log.v("qqqq", HttpJsonAdapter.getInstance()
										.toJson(answerBean));
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// 未提交
							if (!answerBean.getIsFinish().equals("2")) {
								btn01.setText("提交");
								btn01.setBackgroundResource(R.drawable.btn_blue);
								btn01.setVisibility(View.VISIBLE);
								btn01.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										if ("0".equals(answerBean.getIsFinish())) {
											Toast.makeText(mContext,
													"该问卷尚未回答完毕，无法提交，请继续回答后再提交",
													Toast.LENGTH_LONG).show();
											return;
										} else {
											new Handler().postDelayed(new Runnable() {
												@Override
												public void run() {
													// TODO Auto-generated method stub
													((SubTaskActivity) mContext)
													.submitAnswer(
															mdatas.get(position)
																	.getTemplate_ID(),
															mdatas.get(position)
																	.getSubTask_ID());
												}
											}, 1000);
											
										}
									}
								});

								btn02.setBackgroundResource(R.drawable.btn_cyan);
								btn02.setVisibility(View.VISIBLE);

								if (answerBean.getAnswerType().equals("0")) {
									// 手动答题
									btn02.setText("修改");
								} else {
									// 自动答题
									btn02.setText("补答");
								}
								btn02.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										Intent intent = new Intent(mContext,
												AnswerQuestionActivity.class);
//										intent.putExtra("flag",
//												answerBean.getAnswerType()
//														.equals("0") ? "1"
//														: "2");
										intent.putExtra("flag", "1");
										intent.putExtra("type", "1");
										intent.putExtra("Template_ID", mdatas
												.get(position).getTemplate_ID());
										intent.putExtra("taskid",
												mdatas.get(position)
														.getTask_ID());
										intent.putExtra("subtaskid", mdatas
												.get(position).getSubTask_ID());
										intent.putExtra("taskName", mdatas.get(position).getTemplateName());
										mContext.startActivity(intent);
									}
								});

								break;
							}
							// 已提交
							if (answerBean.getIsFinish().equals("2")) {

								btn02.setText("查看");
								btn02.setBackgroundResource(R.drawable.btn_cyan);
								btn02.setVisibility(View.VISIBLE);
								btn02.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View arg0) {
										Intent intent = new Intent(mContext,
												QuestionDetailActivity.class);
										QuestionAnswerDao answerDao = new QuestionAnswerDao(
												mContext);
										ArrayList<QuestionAnswerBean> answerlist = answerDao
												.queryBySql("select * from "
														+ QuestionAnswerBean.TABLENAME
														+ " where Task_ID='"
														+ mdatas.get(position)
																.getTask_ID()
														+ "' and SubTask_ID='"
														+ mdatas.get(position)
																.getSubTask_ID()
														+ "' and Submiter='"
														+ userMobile
														+ "'");
										intent.putExtra("type", "1");
										intent.putExtra("answerlist",
												answerlist);
										intent.putExtra("taskid",
												mdatas.get(position)
														.getTask_ID());
										intent.putExtra("Template_ID", mdatas
												.get(position).getTemplate_ID());
										intent.putExtra("taskName", mdatas.get(position).getTemplateName());
										mContext.startActivity(intent);
									}
								});
								btn01.setVisibility(View.GONE);
								break;
							}
						}
					} else {
						btn01.setText("自动");
						btn01.setBackgroundResource(R.drawable.btn_blue);
						btn01.setVisibility(View.GONE);
						btn01.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								mLoadingDialog.show();
								new Handler().postDelayed(new Runnable() {
									@Override
									public void run() {
										// TODO Auto-generated method stub
										((SubTaskActivity) mContext).autoAnswer(mdatas
												.get(position).getTemplate_ID(), mdatas
												.get(position).getSubTask_ID());
									}
								}, 1000);
								
								SubTaskAdapter.this.notifyDataSetChanged();
							}
						});
						btn02.setText("答题");
						btn02.setBackgroundResource(R.drawable.btn_cyan);
						btn02.setVisibility(View.VISIBLE);
						btn02.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								Intent intent = new Intent(mContext,
										AnswerQuestionActivity.class);
								intent.putExtra("Template_ID",
										mdatas.get(position).getTemplate_ID());
								intent.putExtra("type", "1");
								intent.putExtra("taskid", mdatas.get(position)
										.getTask_ID());
								intent.putExtra("subtaskid",
										mdatas.get(position).getSubTask_ID());
								intent.putExtra("taskName", mdatas.get(position).getTemplateName());
								mContext.startActivity(intent);
							}
						});

					}

				}
			}.execute();

		}
		mViewHolder.btnpreview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext, PreviewQuestionActivity.class);
				intent.putExtra("Template_ID", mdatas.get(position).getTemplate_ID());
				intent.putExtra("taskid", mdatas.get(position).getTask_ID());
				intent.putExtra("taskName", mdatas.get(position).getTemplateName());
				mContext.startActivity(intent);
			}
		});
		return convertView;

	}

	public final class ViewHolder {

		public TextView templateNameTextView;
		public TextView taskdescTextView;
		public Button btn01;
		public Button btn02;
		public Button btnpreview;
	}

	
	private String getSPString(String str){
		SharedPreferences sp=mContext.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString(str, "");
	}
}
